package com.study.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import java.util.HashMap;
import java.util.Map;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author tanglingyu
 * @Date: 2021/10/08/ 16:16
 * @Description
 */
@RestController
public class TestSentinel {

  @GetMapping(value = "/hello")
  public String hello() {
    return "Hello Sentinel";
  }

  @SentinelResource("resource")
  @RequestMapping("/sentinel/hello")
  public Map<String, Object> hello2() {
    Map<String, Object> map = new HashMap<>(2);
    map.put("appName", "sb");
    map.put("method", "hello");
    return map;
  }

  /**
   * @SentinelResource 注解包含以下属性：
   * value: 资源名称,必需项（不能为空）
   * entryType:入口类型，可选项（默认为 EntryType.OUT）
   * blockHandler:blockHandlerClass中对应的异常处理方法名。参数类型和返回值必须和原方法一致
   * blockHandlerClass：自定义限流逻辑处理类
   */
  //通过注解限流并自定义限流逻辑
  @SentinelResource(value = "resource2", blockHandler = "handleException", blockHandlerClass = {
      ExceptionUtil.class})
  @RequestMapping("/sentinel/test2")
  public Map<String, Object> test2() {
    Map<String, Object> map = new HashMap<>();
    map.put("method", "test2");
    map.put("msg", "自定义限流逻辑处理");
    return map;
  }

  public static class ExceptionUtil {
    public static Map<String, Object> handleException(BlockException ex) {
      Map<String, Object> map = new HashMap<>();
      System.out.println("Oops: " + ex.getClass().getCanonicalName());
      map.put("Oops", ex.getClass().getCanonicalName());
      map.put("msg", "通过@SentinelResource注解配置限流埋点并自定义处理限流后的逻辑");
      return map;
    }
  }
}
